<?php
/**
 * By   :    Robert Wilson Nargetey
 * Date :    5/12/12
 * Time :    2:03 PM
 * File :    Score.php
 * Class:    Score
 */
class Score extends Database
{
    private $table = 'scores';

    public function save($data)
    {
        return parent::insert($this->table, $data);
    }

    public function prepareAndSaveScore($data)
    {
        $c = 0;
        if (is_null($this->alreadyParticipated())) {
            if (is_array($data)) {
                $majorIds = array();
                $preparedData = array();
                foreach ($data as $qid => $oid) {
                    if (preg_match('/question_id_\d+/i', $qid)) {
                        $preparedData['question_id'] = substr($qid, 12);
                        $r = explode(':', $oid);
                        $preparedData['objective_id'] = $r[0];
                        $preparedData['recomendation_group_id'] = $r[1];
                        array_push($majorIds, $r[1]);
                        $preparedData['user_id'] = Session::get('uid');

                        $this->save($preparedData);
                        $c++;
                    }
                }
                return $this->computeMajor($majorIds, $c);
            }
        } else {
            return '<b>You have already answered some questions</b>';
        }
    }

    private function computeMajor($majorIds, $c) {
        $count=array_count_values($majorIds);
        arsort($count);
        $keys=array_keys($count);
        return $this->getMajorByRecommendationGroupId($keys[0]);
        //$Major = new Majors();

        //$m = $this->findById('recomendation_groups', false, $keys[0]);
        //return $c . ' Question(s) were answered and your major is: ' . $m->group;
    }

    private function getMajorByRecommendationGroupId($rgId=null) {
        if (!is_null($rgId)) {
            return $this->find('majors', 'WHERE `recomendation_group_id` = ' . $this->escapeValue($rgId));
        }
    }

    private function alreadyParticipated()
    {
        $uid = Session::get('uid');
        return parent::find($this->table, 'WHERE `user_id` = ' . $uid);
    }

    public function findMajorGroup($gid = null) {
        if (!is_null($gid)) {
            return $this->findById('recomendation_groups', false, $gid);
        }
    }

    public function getMajorCategory($mcid = null) {
        if (!is_null($mcid)) {
            return $this->findById('major_categories', false, $mcid);
        }
    }

}
